import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @ClassName Application
 * @Author Alex2
 * @Date 2025/3/6 16:54
 * @Description 将文件从一个路径复制到另一个路径
 **/
public class copySingleFile {
    public static void main(String[] args) {
        File sourceFile = new File("C:/Users/Alex2/Desktop/source/edge-API文档.docx");
        File targetFile = new File("C:/Users/Alex2/Desktop/target/edge-API文档.docx");

        if (copyFile(sourceFile, targetFile)) {
            System.out.println("文件复制成功：" + targetFile.getAbsolutePath());
        } else {
            System.out.println("文件复制失败！");
        }
    }

    public static boolean copyFile(File sourceFile, File targetFile) {
        if (!sourceFile.exists() || !sourceFile.isFile()) {
            System.out.println("源文件不存在或不是文件：" + sourceFile.getAbsolutePath());
            return false;
        }

        File parentFile = targetFile.getParentFile();
        if (!parentFile.exists()) {
            mkdir(parentFile);
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            int byteRead;
            while ((byteRead = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    public static void mkdir(File file) {
        if (file != null && !file.exists()) {
            boolean mkdirs = file.mkdirs();  // 创建目标目录
            if (mkdirs) {
                System.out.println("目标文件夹不存在，已新建目录：" + file.getAbsolutePath());
            } else {
                System.out.println("新建目录失败：" + file.getAbsolutePath());
            }
        }
    }
}
